<template>
  <div class="body">
    <div class="select-subject">
      <div class="mb-2 flex items-center text-sm">
        <!-- <el-radio-group v-model="state.selectedSubjectId" class="ml-4" @change="onChangesubject"> -->
        <el-radio-group v-model="state.selectedSubjectId" class="ml-4">
          <el-radio-button label="初中数学" size="small" value="初中数学" />
          <!-- <el-radio-button label="初中科学" size="small" value="初中科学" />
          <el-radio-button label="初中英语" size="small" value="初中英语" /> -->
        </el-radio-group>
      </div>
    </div>  
    <div  class="menu">      
        <el-menu  class="el-menu-vertical-demo" background-color="#ffffff" :unique-opened="uniqueOpened" :default-openeds="OpendsList">
            <template v-for="courseitem in state.chapterSectionMenu" :key="courseitem.id">
                <el-sub-menu v-if="courseitem.children.length > 0" :key="courseitem.id" :index="courseitem.id.toString()">`
                    <template #title>
                      <router-link :to="{ path:'/getQuestionsByCourse', query: {id: courseitem.id}}">{{ courseitem.name}}</router-link>
                    </template> 
                    <template v-for="chapter_item in courseitem.children" :key="chapter_item.id">
                      <el-sub-menu v-if="chapter_item.children.length > 0" :key="chapter_item.id" :index="chapter_item.id.toString()">
                        <template #title>
                          <router-link :to="{ path:'/getQuestionsByChapter', query: {id: chapter_item.id}}">{{ chapter_item.name}}</router-link>
                        </template>
                        <template v-for="knowledgepointitem in chapter_item.children" :key="knowledgepointitem.id">
                          <el-menu-item @click="SelectKnowledge(knowledgepointitem.id)" :index="knowledgepointitem.id.toString()">
                            {{ knowledgepointitem.name }}                                      
                          </el-menu-item>
                        </template>
                      </el-sub-menu>
                    </template>
                    
                </el-sub-menu>
            </template>          
        </el-menu>
    </div>
  </div>
</template>
  
<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from '@/utils/axios'
import { useRoute, useRouter } from 'vue-router'
import { localGet, localSet, deepClone } from '@/utils'
const uniqueOpened = ref(true)
const OpendsList = ref(['1','2'])
const subjecnt_value_dic = {初中数学:'1', 初中科学: '2', 初中英语:'3'}
const emit=defineEmits(['submit'])
// 学科改变了,重新根据选中的学科获取章节目录
const onChangesubject = (value)=>{
  console.log('subject change:', value)
  state.selectedSubjectId = subjecnt_value_dic[value]
  console.log('学科id',state.selectedSubjectId)
  getCategoryData()
}
const state = reactive({
  chapterSectionMenu:[],
  subjectList:[],
  selectedSubjectId: '1',
})
const handleSubmitButton=()=>{
//通知组件上的自定义submit事件执行
emit('submit')
}

const router = useRouter()
const props = defineProps({
    menu_list: Array,
});
const SelectKnowledge = (id)=> {
  router.push({path:'/getQuestionsByKnowledgepoint', query:{ id: id}})
}
// 获取某学科下的知识点目录
const getCategoryData=()=>{
  console.log('获取某学科下的知识点目录')
  const chapterSectionMenuCache = localGet('chapterSectionMenuCache'+state.selectedSubjectId)
  const chapterSectionMenuCacheStartTime = localGet('chapterSectionMenuCacheStartTime'+state.selectedSubjectId)
  const currentDate = new Date();
  const currentYear = currentDate.getFullYear()
  const currentMonth = currentDate.getMonth() + 1
  const currentDay = currentDate.getDate()
  const currentTime = currentYear*10000 + currentMonth * 100 + currentDay
  console.log('chapterSectionMenuCache:', chapterSectionMenuCache)
  if(chapterSectionMenuCache!=undefined && chapterSectionMenuCacheStartTime!=undefined && chapterSectionMenuCacheStartTime>20240000){
    const dateDiff = currentTime - chapterSectionMenuCacheStartTime // 获取两个时间的差值（以秒为单位）
    console.log('CacheStartTime:', chapterSectionMenuCacheStartTime)
    console.log('now:', currentDate.getDate())
    console.log('天数：',dateDiff)
    if(dateDiff <= 1){
      if(chapterSectionMenuCache!=[]){
        state.chapterSectionMenu = chapterSectionMenuCache
        return 1
      } 
    }
  }
  let params = {
    subject_id: state.selectedSubjectId,
  }
  axios.get('/knowledgepoints/get_knowledge_all_subject_and_course_for_compose',{ params}).then(res => {
    console.log('获取所有章节知识点：', res)
      if (res.code==200){
          state.chapterSectionMenu = res.data.results
          localSet('chapterSectionMenuCache'+state.selectedSubjectId, res.data.results)
          localSet('chapterSectionMenuCacheStartTime'+state.selectedSubjectId, currentTime) 
      }else{
          console.log("error", res.message)
      }
  })
  .catch((error)=>{
      console.log("获取章节菜单错误：", error)
  })
}
// 获取所有学科，并设置默认选中第一个学科
const getSubjectData = ()=>{
  const subjectListCache = localGet('subjectListCache')
  const subjectListCacheStartTime = localGet('subjectListCacheStartTime')
  const currentDate = new Date();
  if(subjectListCache!=undefined && subjectListCacheStartTime!=undefined){    
    const dateDiff = currentDate.getDate() - subjectListCacheStartTime // 获取两个时间的差值（以秒为单位）
    console.log('subjectListCacheStartTime：',dateDiff)
    if(dateDiff <= 1){
      if(subjectListCache!=[]){
        state.subjectList = subjectListCache
        state.selectedSubjectId = state.subjectList[0].id
        return 1
      } 
    }
  }
  axios.get('/SubjectViewSet').then(res => {
      console.log('获取学科：', res)
        if (res.code==200){
            state.subjectList = res.data.results
            state.selectedSubjectId = state.subjectList[0].id
            localSet('subjectListCache', res.data.results)
            localSet('subjectListCacheStartTime', currentDate.getDate())
        }else{       
            console.log("error", res.message)
        }
    })
    .catch((error)=>{
        console.log("获取章节菜单错误：", error)
    })
}
onMounted(()=>{
  getSubjectData()
  getCategoryData()
})
</script>

<style scoped>
    .menu{
        display: flex;
        flex-flow: column nowrap;
        width: 200px;
        overflow: hidden;
        background-color: #fcf2e6;
    }
    span{
        font-size: 10x;
        color: #000;
    }
    a{
        text-decoration: none;
        color:#333;
        font-family:sans-serif;
        font-size: 12px;
    }
</style>